﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;

using Game.Map;

namespace Game.Surface
{
    public class SurfaceCloudField : AbstractField
    {
        public static readonly DependencyProperty OpacityScaleProperty = DependencyProperty.Register(
            "OpacityScale", typeof(Double), typeof(AbstractField), new PropertyMetadata(0d, OnOpacityScaleChanged));

        static void OnOpacityScaleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var p = d as UIElement;
            Debug.Assert(p != null, "p != null");
            p.Opacity = GetOpacityScale(p);
        }

        public static double GetOpacityScale(UIElement element)
        {
            return (double)element.GetValue(OpacityScaleProperty);
        }

        public static void SetOpacityScale(UIElement element, double value)
        {
            element.SetValue(OpacityScaleProperty, value);
        }

        public SurfaceCloudField(IMapFieldView field)
            : base(field)
        {
            Fill = SurfaceFieldRenderer.CreateCloudBrush(MapField);
            //Stroke = Brushes.Black;
            //StrokeThickness = 0;
            
            UpdateFill();
            field.Changed += (source, args) => UpdateFill();
        }

        void UpdateFill()
        {
            if (MapField.IsVisible)
            {
                if (Opacity == 1)
                {
                    Opacity = 0;
                    StartOpacityAutomation(1, 0, 3);
                }
            }
        }

        void StartOpacityAutomation(double start, double end, double time)
        {
            var a = new DoubleAnimation {From = start, To = end};

            var duration = new Duration(TimeSpan.FromSeconds(time));
            a.EasingFunction = new SineEase();
            a.Duration = duration;

            var sb = new Storyboard {Duration = duration};
            sb.Children.Add(a);

            Storyboard.SetTarget(a, this);
            Storyboard.SetTargetProperty(a, new PropertyPath("OpacityScale"));

            sb.Begin();
        }

        protected override void UpdateBitmap(
            IMapFieldView field, 
            bool force)
        {
        }
        
    }
}
